package com.ygqh.baby.handler;

import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.model.CarPricesResult;
import com.ygqh.baby.model.OrderCommitParam;
import com.ygqh.baby.model.SaveMainOrderParam;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.po.YgCardCouponDetail;
import com.ygqh.baby.po.YgCouponDetail;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.DateConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 〈〉
 *
 * @author guohao
 * @date 2018/12/13 15:38
 * @since 1.0.0
 */
@Component
public class CommitOrderHandler extends BaseCommitOrderHandler {

    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private YgUserAddressService ygUserAddressService;
    @Autowired
    private ShoppingCarHandler shoppingCarHandler;
    @Autowired
    private YgStockService ygStockService;
    @Autowired
    private YgCardCouponDetailService ygCardCouponDetailService;
    @Autowired
    private YgUserBalanceService ygUserBalanceService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgCouponDetailService ygCouponDetailService;
    @Autowired
    private SaveMainOrderHandler saveMainOrderHandler;

    @SuppressWarnings({"unchecked"})
    public Message commitOrder(Long userId, String userName, Long userAddressId, Long couponDetailId, BigDecimal totalPrice, AppType appType, PayType payType,
                               String sourceCode, BigDecimal accountPrice, String formId, String userRemark, Long expressCardId, OrderType orderType,
                               List<YgShoppingCarModel> carList, String platformNo, String identityNo, SalesPlatform salesPlatform) {

        OrderCommitParam commitParam = new OrderCommitParam();
        commitParam.setUserId(userId);
        commitParam.setUserName(userName);
        commitParam.setUserAddressId(userAddressId);
        commitParam.setCouponDetailId(couponDetailId);
        commitParam.setTotalPrice(totalPrice);
        commitParam.setAppType(appType);
        commitParam.setPayType(payType);
        commitParam.setSourceCode(sourceCode);
        commitParam.setAccountPrice(accountPrice);
        commitParam.setFormId(formId);
        commitParam.setUserRemark(userRemark);
        commitParam.setExpressCardId(expressCardId);
        commitParam.setOrderType(orderType);
        commitParam.setPlatformNo(platformNo);
        commitParam.setIdentityNo(identityNo);
        commitParam.setSalesPlatform(salesPlatform);
        if (StringUtil.isNotBlank(sourceCode)) {
            YgUser sourceUser = ygUserService.findBySourceCode(sourceCode);
            if (sourceUser != null && sourceUser.getUserType().equals(UserType.Distributor)) {
                commitParam.setDistribution(true);
            }
        }

        return commitOrder(commitParam, carList);
    }

    public Message commitOrder(OrderCommitParam commitParam, List<YgShoppingCarModel> carList) {


        if (carList == null || carList.size() <= 0) {
            return Message.error(documentConstant.getCAR_IS_EMPTY(), null);
        }

        // 校验收货地址
        Message addressMsg = ygUserAddressService.validateUserAddress(commitParam.getUserId(), commitParam.getUserAddressId(), commitParam.getIdentityNo(),
                carList, commitParam.getOrderType());
        if (!Message.isSuccess(addressMsg)) {
            return addressMsg;
        }

        Message checkProduct = checkProduct(carList);
        if (!checkProduct.getType().equals(Message.Type.success)) {
            return checkProduct;
        }
        Message checkStock = checkStock(carList);
        if (!checkStock.getType().equals(Message.Type.success)) {
            return checkStock;
        }

        Message jiaJiaGouMsg = this.validateJiaJiaGou(carList, commitParam.getSalesPlatform());
        if (!jiaJiaGouMsg.getType().equals(Message.Type.success)) {
            return jiaJiaGouMsg;
        }
        Message validateManZeng = this.validateManZeng(carList, commitParam.getSalesPlatform());
        if (!validateManZeng.getType().equals(Message.Type.success)) {
            return validateManZeng;
        }

        CarPricesResult carPrices = shoppingCarHandler.getCarPrices(carList, commitParam.getFormId(), commitParam.getCouponDetailId(), commitParam.getSalesPlatform());

        YgCardCouponDetail expressCard;
        // 验证包邮卡券
        if (carPrices.getExpressPrice().compareTo(BigDecimal.ZERO) > 0 && commitParam.getExpressCardId() != null) {
            expressCard = ygCardCouponDetailService.findById(commitParam.getExpressCardId());
            if (expressCard == null || expressCard.getUseStatus().equals(UseStatus.Used)) {
                return Message.error("包邮卡券异常，请重试", null);
            }
            if (expressCard.getEndDate().before(DateConvertUtils.getDateStart(new Date()))) {
                return Message.error("包邮卡券过期，请重试", null);
            }
            carPrices.setExpressPrice(BigDecimal.ZERO);
        }

        /*
          1、 优惠优先级按 满减、特例品，优惠券、运费顺序来。
          如：现有活动为满100-5，满199包邮，且用户有满200-50的优惠券，这时如果用户的初始订单金额为250，
          最后用户需要支付的金额计算过程为： 250-5=245>200(满足优惠券使用条件)
          245-50=195<199（不满足包邮条件，需加收运费） 195+10=205（用户最后需要支付的金额）
         */
        BigDecimal couponPrice = BigDecimal.ZERO;
        YgCouponDetail couponDetail;
        if (carPrices.getCoupon() != null) {
            couponDetail = ygCouponDetailService.findById(commitParam.getCouponDetailId(), commitParam.getUserId());
            if (couponDetail == null) {
                return Message.error("优惠券有误。", null);
            }
            if (couponDetail.getCouponBatchId().equals(436L) || couponDetail.getCouponBatchId().equals(435L)) {
                long count = carList.stream().filter(car -> car.getSalesType().equals(PromotionType.ManZeng)).count();
                if (count > 0) {
                    return Message.error("优惠券与满增活动冲突", couponDetail.getCouponBatchId());
                }
            }
            couponPrice = carPrices.getCoupon().getFaceValue();
        }

        // 特例品不参与优惠券
        BigDecimal subtract = carPrices.getProductPrice().subtract(carPrices.getSpecialPrice())
                .subtract(couponPrice);
        if (subtract.compareTo(BigDecimal.ZERO) < 0) {
            subtract = BigDecimal.ZERO;
        }
        BigDecimal realTotalPrice = subtract.add(carPrices.getSpecialPrice()).subtract(carPrices.getNewCustomDisPrice()).
                subtract(carPrices.getPackDisPrice()).add(carPrices.getExpressPrice())
                .subtract(carPrices.getManJianPrice());

        if (realTotalPrice.compareTo(commitParam.getTotalPrice()) != 0) {
            return Message.error("订单金额有误。", realTotalPrice);
        }


        Message message = checkAccountPrice(commitParam.getAccountPrice(), realTotalPrice, commitParam.getUserId());
        if (!message.getType().equals(Message.Type.success)) {
            return message;
        }
        SaveMainOrderParam saveMainOrderParam = buildSaveMainOrderParam(commitParam, null, carPrices.getManJianPrice(), couponPrice, carPrices.getExpressPrice());
        return saveMainOrderHandler.saveMainOrder(saveMainOrderParam);


    }


    private SaveMainOrderParam buildSaveMainOrderParam(OrderCommitParam commitParam, Long releationId, BigDecimal manjianPrice,
                                                       BigDecimal yhqPrice, BigDecimal expressPrice) {
        SaveMainOrderParam saveMainOrderParam = new SaveMainOrderParam();
        saveMainOrderParam.setUserId(commitParam.getUserId());
        saveMainOrderParam.setUserName(commitParam.getUserName());
        saveMainOrderParam.setAddressId(commitParam.getUserAddressId());
        saveMainOrderParam.setCouponDetailId(commitParam.getCouponDetailId());
        saveMainOrderParam.setTotalPrice(commitParam.getTotalPrice().subtract(commitParam.getAccountPrice()));
        saveMainOrderParam.setAccountPrice(commitParam.getAccountPrice());
        saveMainOrderParam.setIdentityNo(commitParam.getIdentityNo());
        saveMainOrderParam.setSalesPlatform(commitParam.getSalesPlatform());
        saveMainOrderParam.setAppType(commitParam.getAppType());
        saveMainOrderParam.setPayType(commitParam.getPayType());
        saveMainOrderParam.setFormId(commitParam.getFormId());
        saveMainOrderParam.setUserRemark(commitParam.getUserRemark());
        saveMainOrderParam.setExpressCardId(commitParam.getExpressCardId());
        saveMainOrderParam.setOrderType(commitParam.getOrderType());
        saveMainOrderParam.setSourceCode(commitParam.getSourceCode());
        saveMainOrderParam.setReleationId(releationId);
        saveMainOrderParam.setManjinPrice(manjianPrice);
        saveMainOrderParam.setYhqPrice(yhqPrice);
        saveMainOrderParam.setExpressPrice(expressPrice);
        saveMainOrderParam.setDistribution(commitParam.isDistribution());
        saveMainOrderParam.setReduceStockFlag(true);
        saveMainOrderParam.setPlatformNo(commitParam.getPlatformNo());
        return saveMainOrderParam;
    }

    @Override
    public Message checkProduct(List<YgShoppingCarModel> carList) {
        for (YgShoppingCarModel car : carList) {
            if (ProductStatus.InStock.equals(car.getSaleStatus()) || DataStatus.Delete.equals(car.getSkuStatus())) {
                return Message.error("亲，你购买商品已下架。", car.getProductName());
            }
        }
        return Message.success(null);
    }
}
